﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ProjectSem40701.Util;
using System.Collections;
using System.Data;
using System.Web.Security;

namespace ProjectSem40701
{
    public partial class Test : System.Web.UI.Page
    {
        //khai bao mot so hang so ve trang thai cua user
        private const int Unknow_Error = 0;
        private const int Exist_In_User_Round_But_InActive = 1;
        private const int Not_Exist_In_User_Round = 2;
        private const int Exist_In_User_Round_AndActive = 3;

        //diem thi
        double mark = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
               //kiem tra xem thi sinh da dang nhap chua
                CheckUserLogined objCheckUserLogined = new CheckUserLogined();
                if (objCheckUserLogined.IsUserLogined() == false)
                {
                    //Bao chua dang nhap
                    this.MultiView1.ActiveViewIndex = 0;
                    this.lblError.Text = "Bạn chưa đăng nhập.";
                }
                else
                { 
                    //kiem tra xem co ky thi nao duoc active hay khong
                    CheckActiveExam objCheckActiveExam = new CheckActiveExam();
                    if (objCheckActiveExam.Is_Exist_Exam_Active())
                    {
                        //Lay ra ky thi hien tai
                        GetActiveExamID objGetActiveExamID = new GetActiveExamID();
                        int examID = objGetActiveExamID.ExamID();

                        //kiem tra xem co vong thi nao duoc active hay khong
                        CheckActiveRound objCheckActiveRound = new CheckActiveRound();
                        if (objCheckActiveRound.IsExistRound(examID))
                        {
                            //Lay ra vong thi hien tai
                            GetActiveRoundID objGetActiveRoundID = new GetActiveRoundID();
                            int roundID = objGetActiveRoundID.RoundID(examID);
                            Session["roundID"] = roundID;
                            Session["roundStartTime"] = objGetActiveRoundID.RoundStartTime(examID);
                            Session["roundDuration"] = objGetActiveRoundID.roundDuration(examID);
                            Session["roundEndTime"] = Convert.ToDateTime(Session["roundStartTime"].ToString()).AddMinutes(Convert.ToDouble(Session["roundDuration"].ToString())).ToString();

                            //kiem tra xem user co duoc phep vao thi hay khong

                            //Kiem tra xem vong thi kich hoat co phai vong dau tien khong
                            //neu la vong dau tien thi cho vao thi tu do  
                            CheckRoundIsFirst objCheckRoundIsFirst = new CheckRoundIsFirst();
                            if (objCheckRoundIsFirst.IsRoundFirst(roundID))
                            {
                                //chuyen sang view preload de san sang cho vao thi
                                CheckValidUser objCheckValidUser = new CheckValidUser();
                                if (objCheckValidUser.IsValidUser() != Exist_In_User_Round_But_InActive)
                                {
                                    this.MultiView1.ActiveViewIndex = 1;
                                }
                                else
                                {
                                    this.MultiView1.ActiveViewIndex = 0;
                                    this.lblError.Text = "Bạn đã tham dự vòng thi này hoặc không được quyền tham dự vòng thi này.";
                                }
                            }
                            //neu khong phai vong thi dau thi kiem tra user phai nam trong
                            //bang UserRound va trang thai kich hoat
                            else
                            {
                                CheckValidUser objCheckValidUser = new CheckValidUser();
                                switch (objCheckValidUser.IsValidUser())
                                {
                                    case Not_Exist_In_User_Round:
                                        this.MultiView1.ActiveViewIndex = 0;
                                        this.lblError.Text = "Bạn không đủ điều kiện tham dự vòng thi này.";
                                        break;
                                    case Exist_In_User_Round_But_InActive:
                                        this.MultiView1.ActiveViewIndex = 0;
                                        this.lblError.Text = "Bạn đã tham dự vòng thi này hoặc không được quyền tham dự vòng thi này.";
                                        break;
                                    case Unknow_Error:
                                        this.MultiView1.ActiveViewIndex = 0;
                                        this.lblError.Text = "Lỗi không xác định.";
                                        break;
                                    case Exist_In_User_Round_AndActive:
                                        //chuyen sang view preload de san sang cho vao thi
                                        this.MultiView1.ActiveViewIndex = 1;
                                        break;
                                    default:
                                        this.MultiView1.ActiveViewIndex = 0;
                                        this.lblError.Text = "Lỗi không xác định.";
                                        break;
                                }
                            }
                        }
                        else
                        {
                            //bao khong co vong thi nao ton tai    
                            this.MultiView1.ActiveViewIndex = 0;
                            this.lblError.Text = "Không có vòng thi nào được kích hoạt.";
                        }
                    }
                    else
                    {
                        //bao khong co ky thi nao ton tai    
                        this.MultiView1.ActiveViewIndex = 0;
                        this.lblError.Text = "Không có kỳ thi nào được kích hoạt.";
                    }
                }
            }
        }

        /// <summary>
        /// Su kien xay ra khi view pre-load duoc kich hoat
        /// </summary>
        protected void ViewPreLoadData_Activate(object sender, EventArgs e)
        {
            //neu chua den gio thi
            if (DateTime.Compare(DateTime.Now, Convert.ToDateTime(Session["roundStartTime"].ToString())) < 0)
            {
                //kich hoat dem gio
                this.countDownTimerStartTime.Enabled = true;
            }

            //neu da den gio thi hoac het gio thi
            else
            {
                //neu da qua thoi diem ket thuc vong thi
                if (DateTime.Compare(DateTime.Now, Convert.ToDateTime(Session["roundEndTime"].ToString())) > 0)
                {
                    //bao het gio
                    this.MultiView1.ActiveViewIndex = 0;
                    this.lblError.Text = "Thời gian làm bài thi đã kết thúc.";
                }
                else
                {
                    //Chuyen sang view load bai thi
                    this.MultiView1.ActiveViewIndex = 2;
                }
            }
        }
        /// <summary>
        /// khi timer o view preload tick
        /// </summary>
        protected void countDownTimerStartTime_Tick(object sender, EventArgs e)
        {
            TimeSpan timeRemain = Convert.ToDateTime(Session["roundStartTime"].ToString()).Subtract(DateTime.Now);
            this.lblTimeRemain.Text = "Còn " + timeRemain.Days.ToString() + " ngày " + timeRemain.Hours + " giờ " + timeRemain.Minutes + " phút " + timeRemain.Seconds + " giây ";

            //Neu gio hien tai lon hon hoac bang voi start time
            if (DateTime.Compare(DateTime.Now, Convert.ToDateTime(Session["roundStartTime"].ToString())) >= 0)
            {
                //Chuyen sang view load bai thi
                this.MultiView1.ActiveViewIndex = 2;
            }
        }

        /// <summary>
        /// su kien databinding cua ltrContent (noi dung cau hoi)
        /// </summary>
        protected void ltrContent_DataBinding(object sender, EventArgs e)
        {
            Literal ltrContent = sender as Literal;
            ltrContent.Text = Server.HtmlDecode(ltrContent.Text.Trim());
        }

        /// <summary>
        /// su kien databinding cua chkbCorrect (noi dung cau tra loi)
        /// </summary>
        protected void chkbCorrect_DataBinding(object sender, EventArgs e)
        {
            CheckBox chkbCorrect = sender as CheckBox;
            chkbCorrect.Text = Server.HtmlDecode(chkbCorrect.Text.ToString());
        }

        /// <summary>
        /// Khi nguoi dung submit bai thi
        /// </summary>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            CalculateMark();
        }
        /// <summary>
        /// su kien tick cua timerCountDown
        /// </summary>
        protected void timerCountDown_Tick(object sender, EventArgs e)
        {
            try
            {
                TimeSpan dtRemain = Convert.ToDateTime(Session["roundEndTime"]).Subtract(DateTime.Now);
                this.lblTimeRemain2.Text =
                    (dtRemain.Hours > 9 ? dtRemain.Hours.ToString() : "0" + dtRemain.Hours.ToString()) + " : " +
                    (dtRemain.Minutes > 9? dtRemain.Minutes.ToString():"0" + dtRemain.Minutes.ToString()) +" : "+
                    (dtRemain.Seconds > 9 ? dtRemain.Seconds.ToString() : "0" + dtRemain.Seconds.ToString());
                if (dtRemain.TotalSeconds <= 0) //het gio
                {
                    CalculateMark();
                    if (this.timerCountDown.Enabled == true)
                    {
                        this.timerCountDown.Enabled = false;
                    }
                }
            }
            catch
            {
                //thông báo lỗi
            }
        }

        /// <summary>
        /// Cham diem o day
        /// </summary>
        private void CalculateMark()
        {
            try
            {
                for (int i = 0; i < this.grvQA.Rows.Count; i++)
                {
                    int questionID;
                    ArrayList ansIDs = new ArrayList();
                    double questionMark;
                    ArrayList ansIDsCorrect = new ArrayList();

                    //----------------Lay ra diem va ma cau hoi----------------//

                    Literal ltrMark = grvQA.Rows[i].FindControl("ltrMark") as Literal;
                    Label lblQID = grvQA.Rows[i].FindControl("lblQID") as Label;
                    GridView grvAns = grvQA.Rows[i].FindControl("grvAnswer") as GridView;

                    questionID = Convert.ToInt32(lblQID.Text);
                    questionMark = Convert.ToDouble(ltrMark.Text);

                    //--------------Lay ra nhung cau tra loi ma nguoi dung da chon---------------//

                    for (int j = 0; j < grvAns.Rows.Count; j++)
                    {
                        CheckBox chkbCorrect = (CheckBox)grvAns.Rows[j].FindControl("chkbCorrect");
                        Literal ltrAnsID = grvAns.Rows[j].FindControl("ltrAnsID") as Literal;
                        if (chkbCorrect.Checked == true)
                        {
                            ansIDs.Add(ltrAnsID.Text);
                        }
                    }
                    
                    //-------------Lay ra nhung cau tra loi dung--------------//

                    GetCorrectAnswers objGetCorrectAnswers = new GetCorrectAnswers();
                    DataTable dttblCorrectAnswers = objGetCorrectAnswers.getCorrectAns(questionID);
                    for (int k = 0; k < dttblCorrectAnswers.Rows.Count; k++)
                    {
                        ansIDsCorrect.Add(dttblCorrectAnswers.Rows[k]["AnswerID"].ToString());
                    }
                    
                    //-----------So sanh cau tra loi dung voi cau tra loi da chon-------------//

                    CompareArrayList objCompareArrayList = new CompareArrayList();
                    if (objCompareArrayList.compareArrlst(ansIDs, ansIDsCorrect))
                    {
                        this.mark += questionMark;
                    }

                    //Lay ra ma vong thi va ma thi sinh
                    int rid = Convert.ToInt32(Session["roundID"].ToString());
                    string strUser = System.Web.HttpContext.Current.User.Identity.Name;
                    Guid userID = new Guid(Membership.GetUser(strUser).ProviderUserKey.ToString());

                    //----------------Luu diem vao db---------------//

                    SaveMark objSaveMark = new SaveMark();
                    objSaveMark.saveMark(this.mark, rid, userID);
                    this.MultiView1.ActiveViewIndex = 3;
                    this.lblComplete.Text = "Điểm của bạn đã được lưu vào cơ sở dữ liệu của chúng tôi. Kết quả sẽ được thông báo cho bạn sớm.";
                }
            }
            catch
            {
                //thong bao loi
            }
        }

        protected void grvQA_DataBound(object sender, EventArgs e)
        {
            for (int i = 0; i < grvQA.Rows.Count; i++)
            {
                Literal ltrQuestionTittle = grvQA.Rows[i].FindControl("ltrQuestionTittle") as Literal;
                ltrQuestionTittle.Text = "Câu " + (i + 1) + ": ";

                GridView grvAns = grvQA.Rows[i].FindControl("grvAnswer") as GridView;
                grvAns.DataBind();
            }
        }

        /// <summary>
        /// View lam bai thi duoc load
        /// </summary>
        protected void ViewLoadData_Activate(object sender, EventArgs e)
        {
            int rid = Convert.ToInt32(Session["roundID"].ToString());
            
            //bind du lieu vao grid
            GetQuestions objGetQuestions = new GetQuestions();
            this.grvQA.DataSource = objGetQuestions.getQuestions(rid);
            this.grvQA.DataBind();

            string duration = Session["roundDuration"].ToString();
            this.lblTotalTime.Text = duration + " phút.";
        }
    }
}
